package net.wang.spring.data.mongo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.wang.spring.data.mongo.domain.User;
import net.wang.spring.data.mongo.repo.UserRepo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    UserRepo userRepo;

    @Autowired
    MongoTemplate mongoTemplate;

    @PostMapping
    public ResponseEntity save(@RequestBody User user) {
        log.info("user {}", user);
        return ResponseEntity.ok(userRepo.save(user));
    }

    @GetMapping
    public ResponseEntity query() {
        List<User> users = mongoTemplate.find(new Query().addCriteria(Criteria.where("role.$id").is(new ObjectId("5d41aca25427c61a60d764d3"))), User.class);
        return ResponseEntity.ok(users);
    }

    @GetMapping("/list")
    public ModelAndView get() throws JsonProcessingException {
        Pageable pageable = PageRequest.of(0, 10);
        List<User> users = mongoTemplate.find(new Query().with(pageable).addCriteria(Criteria.where("role.$id").is(new ObjectId("5d41aca25427c61a60d764d3"))), User.class);
        long count = mongoTemplate.count(new Query().addCriteria(Criteria.where("role.$id").is(new ObjectId("5d41aca25427c61a60d764d3"))), User.class);

        PageImpl<User> page = new PageImpl<>(users, pageable, count);

        return new ModelAndView("/list","pageRequest",page);

    }


}
